package com.dc.commons.jdbc;

import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

import com.dc.commons.utils.Reflections;

/*******************************************************************************<P>
 * 文件名: SimpleRowMapper.java <br>
 * 版本: 1.0<br>
 * 描述: 简单的将结果集返回指定的对象<br>
 * 版权所有: <br>
 * <P>
 * 创建者: 王建栋 <br>
 * 创建日期: 2016年5月4日 下午1:55:50<br>
 * 修改者: <br>
 * 修改日期: <br>
 * 修改说明: <br>
 ******************************************************************************/
public class SimpleRowMapper<T> implements RowMapper<T>{
	private final Class<?> clazz;
	public SimpleRowMapper(Class<?> clazz){
		this.clazz=clazz;
	}

	/* (non-Javadoc)
	 * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		T t=null;
		try {
			t = (T) clazz.newInstance();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		ResultSetMetaData metaData=rs.getMetaData();
		for(int i=0;i<metaData.getColumnCount();i++){
			String columnName=metaData.getColumnName(i+1);
			columnName=StringUtils.uncapitalize(columnName);
			if(columnName.indexOf("_")!=-1){
				columnName=JdbcUtils.convertUnderscoreNameToPropertyName(columnName);
			}
			Class<?> clazz=Reflections.getAccessibleMethodByName(t, columnName).getReturnType();
			Reflections.invokeSetter(t, columnName, getResultValue(rs, i+1,clazz));
			
		}
		return t;
	}
	
	/**
	 * 
	 * @param rs
	 * @param index
	 * @return resultValue
	 * @throws SQLException
	 */
	private Object getResultValue(ResultSet rs,int index,Class<?> clazz)throws SQLException{
		Object obj=null;
		if(Number.class.isAssignableFrom(clazz)){
			if(clazz==Double.class){
				obj=rs.getDouble(index);
			}else if(clazz==Long.class){
				obj=rs.getLong(index);
			}else if(clazz==Integer.class){
				obj=rs.getInt(index);
			}else if(clazz==Float.class){
				obj=rs.getFloat(index);
			}else if(clazz==Short.class){
				obj=rs.getShort(index);
			}else if(clazz==Byte.class){
				obj=rs.getByte(index);
			}
		}else if(Date.class.isAssignableFrom(clazz)){
			obj=rs.getTimestamp(index);
		}else if(String.class.isAssignableFrom(clazz)){
			obj=rs.getObject(index);
			if(obj instanceof Clob){
				Clob clob = (Clob) obj;
				obj = clob.getSubString(1, (int) clob.length());
			}else{
				obj=rs.getString(index);
			}
		}else{
			obj= JdbcUtils.getResultSetValue(rs, index);
		}
		return obj;
	}
	
}
